<template>
  <div class="node-form">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      :disabled="mode === 'view'"
    >
      <!-- 基本信息 -->
      <el-card class="form-section" shadow="never">
        <template #header>
          <span class="section-title">基本信息</span>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="节点编码" prop="nodeCode">
              <el-input
                v-model="formData.nodeCode"
                placeholder="请输入节点编码"
                :disabled="mode === 'edit'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="节点名称" prop="nodeName">
              <el-input
                v-model="formData.nodeName"
                placeholder="请输入节点名称"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="节点类型" prop="nodeType">
              <el-select
                v-model="formData.nodeType"
                placeholder="请选择节点类型"
                style="width: 100%"
              >
                <el-option label="开始节点" value="START" />
                <el-option label="结束节点" value="END" />
                <el-option label="通用节点" value="COMMON" />
                <el-option label="条件节点" value="CONDITION" />
                <el-option label="循环节点" value="LOOP" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="节点分类" prop="category">
              <el-select
                v-model="formData.category"
                placeholder="请选择节点分类"
                style="width: 100%"
              >
                <el-option label="系统内置" value="SYSTEM" />
                <el-option label="HTTP请求" value="HTTP" />
                <el-option label="脚本执行" value="SCRIPT" />
                <el-option label="条件判断" value="CONDITION" />
                <el-option label="数据处理" value="DATA" />
                <el-option label="业务逻辑" value="BUSINESS" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="图标" prop="icon">
              <el-input
                v-model="formData.icon"
                placeholder="请输入图标名称"
              >
                <template #prepend>
                  <el-icon><component :is="formData.icon || 'Document'" /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="颜色" prop="color">
              <el-color-picker v-model="formData.color" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="组件类名" prop="componentClass">
              <el-input
                v-model="formData.componentClass"
                placeholder="请输入组件类名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本号" prop="version">
              <el-input
                v-model="formData.version"
                placeholder="请输入版本号"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="节点描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入节点描述"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="系统内置">
              <el-switch
                v-model="formData.isSystemBuiltIn"
                :disabled="mode !== 'add'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-switch
                v-model="formData.status"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 输入参数配置 -->
      <el-card class="form-section" shadow="never">
        <template #header>
          <div class="section-header">
            <span class="section-title">输入参数配置</span>
            <el-button
              v-if="mode !== 'view'"
              type="primary"
              size="small"
              @click="openSchemaEditor('input')"
            >
              JSON Schema 编辑器
            </el-button>
          </div>
        </template>
        
        <el-form-item label="输入参数Schema" prop="inputParamsSchema">
          <el-input
            v-model="formData.inputParamsSchema"
            type="textarea"
            :rows="6"
            placeholder="请输入JSON Schema格式的输入参数定义"
          />
        </el-form-item>
      </el-card>

      <!-- 输出参数配置 -->
      <el-card class="form-section" shadow="never">
        <template #header>
          <div class="section-header">
            <span class="section-title">输出参数配置</span>
            <el-button
              v-if="mode !== 'view'"
              type="primary"
              size="small"
              @click="openSchemaEditor('output')"
            >
              JSON Schema 编辑器
            </el-button>
          </div>
        </template>
        
        <el-form-item label="输出参数Schema" prop="outputParamsSchema">
          <el-input
            v-model="formData.outputParamsSchema"
            type="textarea"
            :rows="6"
            placeholder="请输入JSON Schema格式的输出参数定义"
          />
        </el-form-item>
      </el-card>

      <!-- 配置参数 -->
      <el-card class="form-section" shadow="never">
        <template #header>
          <div class="section-header">
            <span class="section-title">配置参数</span>
            <el-button
              v-if="mode !== 'view'"
              type="primary"
              size="small"
              @click="openSchemaEditor('config')"
            >
              JSON Schema 编辑器
            </el-button>
          </div>
        </template>
        
        <el-form-item label="配置参数Schema" prop="configParamsSchema">
          <el-input
            v-model="formData.configParamsSchema"
            type="textarea"
            :rows="6"
            placeholder="请输入JSON Schema格式的配置参数定义"
          />
        </el-form-item>

        <el-form-item label="默认配置" prop="defaultConfig">
          <el-input
            v-model="formData.defaultConfig"
            type="textarea"
            :rows="4"
            placeholder="请输入JSON格式的默认配置"
          />
        </el-form-item>
      </el-card>

      <!-- 标签和排序 -->
      <el-card class="form-section" shadow="never">
        <template #header>
          <span class="section-title">其他设置</span>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标签">
              <el-select
                v-model="formData.tags"
                multiple
                filterable
                allow-create
                placeholder="请选择或输入标签"
                style="width: 100%"
              >
                <el-option
                  v-for="tag in commonTags"
                  :key="tag"
                  :label="tag"
                  :value="tag"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sortOrder">
              <el-input-number
                v-model="formData.sortOrder"
                :min="0"
                :max="9999"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button
        v-if="mode !== 'view'"
        type="primary"
        @click="handleSave"
        :loading="saving"
      >
        保存
      </el-button>
      <el-button
        v-if="mode !== 'view'"
        type="success"
        @click="handleSaveAndTest"
        :loading="saving"
      >
        保存并测试
      </el-button>
    </div>

    <!-- Schema编辑器对话框 -->
    <el-dialog
      v-model="schemaEditorVisible"
      :title="schemaEditorTitle"
      width="85%"
      :close-on-click-modal="false"
      draggable
      class="schema-dialog"
    >
      <SchemaEditor
        v-if="schemaEditorVisible"
        :schema="currentSchema"
        :type="currentSchemaType"
        @save="handleSchemaSave"
        @cancel="schemaEditorVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import SchemaEditor from './SchemaEditor.vue'
import * as nodeDefinitionApi from '@/api/nodeDefinition'

// Props
const props = defineProps({
  nodeData: {
    type: Object,
    default: null
  },
  mode: {
    type: String,
    default: 'add', // add, edit, view
    validator: (value) => ['add', 'edit', 'view'].includes(value)
  }
})

// Emits
const emit = defineEmits(['save', 'cancel'])

// 响应式数据
const formRef = ref(null)
const saving = ref(false)
const schemaEditorVisible = ref(false)
const currentSchemaType = ref('')
const currentSchema = ref('')

// 表单数据
const formData = reactive({
  id: null,
  nodeCode: '',
  nodeName: '',
  description: '',
  nodeType: 'COMMON',
  category: 'BUSINESS',
  icon: 'Document',
  color: '#409EFF',
  componentClass: '',
  inputParamsSchema: '',
  outputParamsSchema: '',
  configParamsSchema: '',
  defaultConfig: '',
  version: '1.0.0',
  isSystemBuiltIn: false,
  status: 1,
  tags: [],
  sortOrder: 100
})

// 常用标签
const commonTags = ref([
  '数据处理',
  '业务逻辑',
  '外部接口',
  '条件判断',
  '循环处理',
  '异步处理',
  '缓存',
  '日志',
  '监控',
  '通知'
])

// 表单验证规则
const formRules = {
  nodeCode: [
    { required: true, message: '请输入节点编码', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    {
      pattern: /^[A-Z][A-Z0-9_]*$/,
      message: '节点编码必须以大写字母开头，只能包含大写字母、数字和下划线',
      trigger: 'blur'
    }
  ],
  nodeName: [
    { required: true, message: '请输入节点名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  nodeType: [
    { required: true, message: '请选择节点类型', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择节点分类', trigger: 'change' }
  ],
  componentClass: [
    { required: true, message: '请输入组件类名', trigger: 'blur' }
  ],
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' },
    {
      pattern: /^\d+\.\d+\.\d+$/,
      message: '版本号格式应为 x.y.z',
      trigger: 'blur'
    }
  ],
  inputParamsSchema: [
    { validator: validateJsonSchema, trigger: 'blur' }
  ],
  outputParamsSchema: [
    { validator: validateJsonSchema, trigger: 'blur' }
  ],
  configParamsSchema: [
    { validator: validateJsonSchema, trigger: 'blur' }
  ],
  defaultConfig: [
    { validator: validateJson, trigger: 'blur' }
  ]
}

// 计算属性
const schemaEditorTitle = computed(() => {
  const titles = {
    input: '输入参数Schema编辑器',
    output: '输出参数Schema编辑器',
    config: '配置参数Schema编辑器'
  }
  return titles[currentSchemaType.value] || 'Schema编辑器'
})

// JSON Schema验证器
function validateJsonSchema(rule, value, callback) {
  if (!value) {
    callback()
    return
  }
  
  try {
    const parsed = JSON.parse(value)
    if (typeof parsed !== 'object' || parsed === null) {
      callback(new Error('Schema必须是有效的JSON对象'))
      return
    }
    callback()
  } catch (error) {
    callback(new Error('Schema必须是有效的JSON格式'))
  }
}

// JSON验证器
function validateJson(rule, value, callback) {
  if (!value) {
    callback()
    return
  }
  
  try {
    JSON.parse(value)
    callback()
  } catch (error) {
    callback(new Error('必须是有效的JSON格式'))
  }
}

// 方法定义
const initFormData = () => {
  if (props.nodeData) {
    Object.keys(formData).forEach(key => {
      if (props.nodeData[key] !== undefined) {
        formData[key] = props.nodeData[key]
      }
    })
    
    // 处理字段名映射：后端isSystem -> 前端isSystemBuiltIn
    if (props.nodeData.isSystem !== undefined) {
      formData.isSystemBuiltIn = props.nodeData.isSystem === 1
    }
    
    // 处理字段名映射：后端Schema字段名 -> 前端Schema字段名
    if (props.nodeData.inputSchema !== undefined) {
      formData.inputParamsSchema = props.nodeData.inputSchema
    }
    if (props.nodeData.outputSchema !== undefined) {
      formData.outputParamsSchema = props.nodeData.outputSchema
    }
    if (props.nodeData.configSchema !== undefined) {
      formData.configParamsSchema = props.nodeData.configSchema
    }
    
    // 处理JSON字段的格式化
    if (formData.inputParamsSchema && typeof formData.inputParamsSchema === 'object') {
      formData.inputParamsSchema = JSON.stringify(formData.inputParamsSchema, null, 2)
    }
    if (formData.outputParamsSchema && typeof formData.outputParamsSchema === 'object') {
      formData.outputParamsSchema = JSON.stringify(formData.outputParamsSchema, null, 2)
    }
    if (formData.configParamsSchema && typeof formData.configParamsSchema === 'object') {
      formData.configParamsSchema = JSON.stringify(formData.configParamsSchema, null, 2)
    }
    if (formData.defaultConfig && typeof formData.defaultConfig === 'object') {
      formData.defaultConfig = JSON.stringify(formData.defaultConfig, null, 2)
    }
    if (formData.tags && typeof formData.tags === 'string') {
      try {
        formData.tags = JSON.parse(formData.tags)
      } catch {
        formData.tags = []
      }
    }
  }
}

const openSchemaEditor = (type) => {
  currentSchemaType.value = type
  const schemaMap = {
    input: formData.inputParamsSchema,
    output: formData.outputParamsSchema,
    config: formData.configParamsSchema
  }
  currentSchema.value = schemaMap[type] || ''
  schemaEditorVisible.value = true
}

const handleSchemaSave = (schema) => {
  const schemaMap = {
    input: 'inputParamsSchema',
    output: 'outputParamsSchema',
    config: 'configParamsSchema'
  }
  const field = schemaMap[currentSchemaType.value]
  if (field) {
    formData[field] = schema
  }
  schemaEditorVisible.value = false
}

const handleSave = async () => {
  try {
    await formRef.value.validate()
    await saveNode()
  } catch (error) {
    ElMessage.error('表单验证失败，请检查输入')
  }
}

const handleSaveAndTest = async () => {
  try {
    await formRef.value.validate()
    await saveNode()
    // 触发测试
    // TODO: 实现测试功能
    ElMessage.success('保存成功，即将进入测试模式')
  } catch (error) {
    ElMessage.error('表单验证失败，请检查输入')
  }
}

const saveNode = async () => {
  saving.value = true
  try {
    // 准备提交数据
    const submitData = { ...formData }
    
    // 处理字段名映射：前端isSystemBuiltIn -> 后端isSystem
    if (submitData.isSystemBuiltIn !== undefined) {
      submitData.isSystem = submitData.isSystemBuiltIn ? 1 : 0
      delete submitData.isSystemBuiltIn
    }
    
    // 处理字段名映射：前端Schema字段名 -> 后端Schema字段名
    if (submitData.inputParamsSchema !== undefined) {
      submitData.inputSchema = submitData.inputParamsSchema
      delete submitData.inputParamsSchema
    }
    if (submitData.outputParamsSchema !== undefined) {
      submitData.outputSchema = submitData.outputParamsSchema
      delete submitData.outputParamsSchema
    }
    if (submitData.configParamsSchema !== undefined) {
      submitData.configSchema = submitData.configParamsSchema
      delete submitData.configParamsSchema
    }
    
    // 处理JSON字段 - Schema字段和defaultConfig保持字符串格式，后端期望String类型
    // 只处理其他需要解析的JSON字段
    if (submitData.tags && Array.isArray(submitData.tags)) {
      submitData.tags = JSON.stringify(submitData.tags)
    }

    if (props.mode === 'add') {
      await nodeDefinitionApi.createNodeDefinition(submitData)
      ElMessage.success('创建成功')
    } else if (props.mode === 'edit') {
      await nodeDefinitionApi.updateNodeDefinition(submitData.id, submitData)
      ElMessage.success('更新成功')
    }
    
    emit('save')
  } catch (error) {
    ElMessage.error('保存失败：' + error.message)
  } finally {
    saving.value = false
  }
}

const handleCancel = () => {
  emit('cancel')
}

// 监听props变化
watch(
  () => props.nodeData,
  () => {
    initFormData()
  },
  { immediate: true }
)

// 生命周期
onMounted(() => {
  initFormData()
})
</script>

<style scoped>
.node-form {
  max-height: 70vh;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 20px;
}

.form-section :deep(.el-card__body) {
  padding: 20px;
}

.section-title {
  font-weight: 600;
  color: #303133;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 0;
  border-top: 1px solid #ebeef5;
  margin-top: 20px;
}

:deep(.el-textarea__inner) {
  font-family: 'Courier New', monospace;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

/* Schema编辑器对话框样式 */
.schema-dialog :deep(.el-dialog) {
  max-height: 90vh;
  overflow: hidden;
}

.schema-dialog :deep(.el-dialog__body) {
  max-height: 75vh;
  overflow-y: auto;
  padding: 0;
  box-sizing: border-box;
}

.schema-dialog :deep(.el-dialog__header) {
  flex-shrink: 0;
}
</style>